import json
import socket
import threading
import time

HOST = '127.0.0.1'
PORT = 8080


class UnityManager:
    def __init__(self, cav_world):
        self.cav_world = cav_world
        self.server_socket = None
        self.start()

    def start(self):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind((HOST, PORT))
        self.server_socket.listen(5)
        print(f"Server started on {HOST}:{PORT}")
        # 启动一个线程来处理客户端连接
        client_socket, addr = self.server_socket.accept()
        threading.Thread(target=self.handle_unity_client, args=(client_socket,), daemon=True).start()

        threading.Thread(target=self._accept_clients, daemon=True).start()

    def _accept_clients(self):
        while True:
            client_socket, addr = self.server_socket.accept()
            print(f"Accepted connection from {addr}")
            # 为每个客户端连接创建一个新的线程来处理
            threading.Thread(target=self.handle_unity_client, args=(client_socket,), daemon=True).start()

    def handle_unity_client(self, client_socket):
        try:
            while True:
                request = client_socket.recv(1024).decode()
                if not request:  # 检查是否为空消息（可能是客户端关闭了连接）
                    break  # 跳出循环，关闭连接
                print(f"Received {request}")
                request_parts = request.split(":")

                if request_parts[0] == "PLATOON_DATA" and len(request_parts) == 2:
                    vehicle_id = request_parts[1]
                    platoon_data = self.cav_world.get_platoon_data_by_vid(vehicle_id)
                    vehicle_data = self.cav_world.get_vehicles_pos()
                    lane_density = self.cav_world.get_lane_density()
                    trafficlight_status = self.cav_world.get_trafficlight_data()

                    message = {}
                    if vehicle_data:  # 假设vehicle_data是非空列表或字典等
                        message["VehicleData"] = vehicle_data
                    if lane_density is not None:  # 假设lane_density不是None时表示有数据
                        message["LaneDensity"] = lane_density
                    if platoon_data:  # 假设platoon_data是非空列表或字典等
                        message["PlatoonData"] = platoon_data
                    if trafficlight_status:
                        message["TrafficLightData"] = trafficlight_status
                elif request == "VEHICLE_DATA":
                    vehicle_data = self.cav_world.get_vehicles_pos()
                    lane_density = self.cav_world.get_lane_density()
                    trafficlight_status = self.cav_world.get_trafficlight_data()

                    message = {}
                    if vehicle_data:
                        message["VehicleData"] = vehicle_data
                    if lane_density is not None:
                        message["LaneDensity"] = lane_density
                    if trafficlight_status:
                        message["TrafficLightData"] = trafficlight_status
                else:
                    message = None
                client_socket.sendall(json.dumps(message).encode())
                print("sent all data", message)
        finally:
            client_socket.close()
